
package com.be.beadmin.design.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.design.dto.input.StandFileInfoByStandTypeIdAndCategoryPage;
import com.be.beadmin.design.dto.input.StandFileInfoDto;
import com.be.beadmin.design.dto.output.StandFileInfoEx;
import com.be.beadmin.design.entity.StandFileInfo;
import com.be.beadmin.design.entity.StandFileInfo_;
import com.be.beadmin.design.entity.StandProduct;
import com.be.beadmin.design.mapper.StandFileInfoMapper;
import com.be.beadmin.design.mapper.StandFileInfoMapperEx;
import com.be.beadmin.design.mapper.StandProductMapper;
import com.be.beadmin.design.repository.StandFileInfoRepository;
import com.be.beadmin.design.repository.StandProductRepository;
import com.be.beadmin.design.service.StandFileInfoService;
import com.be.beadmin.design.service.StandProductService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.dto.output.DictDataEx;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.service.repository.DictTypeRepository;
import com.be.beadmin.service.service.DictDataService;
import com.be.beadmin.service.service.SerialNumberService;
import com.google.common.io.ByteStreams;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Jiahao Liu
 * @description 服务实现
 * @date 2023-02-16
 **/
@Service
@RequiredArgsConstructor
public class StandFileInfoServiceImpl implements StandFileInfoService {

    @Autowired
    private StandFileInfoRepository standFileInfoRepository;
    @Autowired
    private StandFileInfoMapper standFileInfoMapper;
    @Autowired
    private StandFileInfoMapperEx standFileInfoExMapper;
    @Autowired
    private StandFileInfoService standFileInfoService;
    @Autowired
    private StandProductRepository standProductRepository;
    @Autowired
    private StandProductService standProductService;
    @Autowired
    private StandProductMapper standProductMapper;
    @Autowired
    private DictTypeRepository dictTypeRepository;

    @Autowired
    private DictDataService dictDataService;

    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    @Override
    public Page<StandFileInfoEx> getStandFileInfoByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<StandFileInfo> page = standFileInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(StandFileInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(StandFileInfo_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<StandFileInfoEx> page1 = page.map(standFileInfoExMapper::toEntity);
        return page1;

    }

    @Override
    public Page<StandFileInfoEx> getStandFileInfoByStandTypeIdAndCategoryPage(StandFileInfoByStandTypeIdAndCategoryPage standFileInfoByStandTypeIdAndCategoryPage) {
        String standTypeId = standFileInfoByStandTypeIdAndCategoryPage.getStandTypeId();
        String category = standFileInfoByStandTypeIdAndCategoryPage.getCategory();
        PageEntity pageEntity = standFileInfoByStandTypeIdAndCategoryPage.getPageEntity();
        if (standTypeId == null) throw new BeadminException("未指定标准柜体id");
        if (category == null) throw new BeadminException("未指定附件类型(BOM或者其他)");

        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<StandFileInfo> page = standFileInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(StandFileInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(StandFileInfo_.standTypeId), standTypeId); //过滤为0
                    list.add(pre3);
                    if (category.equals("BOM")) {
                        Predicate pre4 = criteriaBuilder.equal(root.get(StandFileInfo_.category), category); //过滤为BOM
                        list.add(pre4);
                    } else {
                        //图纸合在一起
                        Predicate pre4 = criteriaBuilder.notEqual(root.get(StandFileInfo_.category), "BOM"); //过滤为非BOM
                        list.add(pre4);
                    }
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(StandFileInfo_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<StandFileInfoEx> page1 = page.map(standFileInfoExMapper::toEntity);
        return page1;
    }

    @Override
    public void switchStandFileInfo(String standFileInfoId, String standTypeId, String category, int status) {

        if (standFileInfoId == null) throw new BeadminException("未指定附件id");
        if (standTypeId == null) throw new BeadminException("未指定标准柜id");
        if (category == null) throw new BeadminException("未指定分类");
        if (status == 0) throw new BeadminException("未指定状态");

        if (status == 1) {
            //关闭其他启用的
            StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId, category, 1, 0);
            if (standFileInfo != null) {
                standFileInfo.setStatus(-1);
                standFileInfoRepository.save(standFileInfo);
            }

            //启用
            standFileInfo = standFileInfoRepository.findStandFileInfoById(standFileInfoId);
            standFileInfo.setStatus(1);
            standFileInfoRepository.save(standFileInfo);
        } else if (status == -1) {
            //关闭
            StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoById(standFileInfoId);
            standFileInfo.setStatus(-1);
            standFileInfoRepository.save(standFileInfo);
        }

        StandProduct standProduct = standProductRepository.findStandProductById(standTypeId);

        StandFileInfo standFileInfoBom = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId, "BOM", 1, 0);
        if (standFileInfoBom != null) standProduct.setIsBomUpload(1);
        else standProduct.setIsBomUpload(0);

        List<String> drawList = dictDataService.getDictDataKeyByDictTypeName("图纸类别");
        if (drawList == null) {
            throw new BeadminException("未找到图纸类别的字典");
        }
        standProduct.setIsDrawingUpload(checkDrawingIsUpload(standProduct));
        standProductRepository.save(standProduct);
    }

    @Override
    public String getPreviewUrl(StandFileInfoDto standFileInfoDto) throws Exception {
        String fileCode = standFileInfoDto.getFileCode();
        String fileName = standFileInfoDto.getFileName();
        String FileName = fileCode + "+" + String.valueOf(standFileInfoDto.getVersion()) + "+" + fileName;
        String preview_url = minioUtil.getPreviewFileUrl(standFileInfoDto.getBucketName(), FileName);


//        standFileInfoDto.setFileUrl(preview_url);
//        StandFileInfo standFileInfo = standFileInfoMapper.toEntity(standFileInfoDto);
//        standFileInfoRepository.save(standFileInfo);
        return preview_url;
    }


    @Override
    public void addStandFileInfo(StandFileInfoDto standFileInfoDto) {
        StandFileInfo result = standFileInfoRepository.findStandFileInfoByIdAndDelete(standFileInfoDto.getId(), 0);
        if (ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("StandFileInfo不存在,请重新查询");
        }
        StandFileInfo standFileInfo = standFileInfoMapper.toEntity(standFileInfoDto);
        standFileInfoRepository.save(standFileInfo);
    }

    @Override
    public List<Object> uploadStandFileInfoBom(String standTypeId, String standTypeDesc, String standTypeCode, String standTypeName, String category, MultipartFile multipartFile, String memo, String bucketName) throws Exception {

        List<Object> returnBomCodeAndVersion = new ArrayList<>();

        StandProduct standProduct = standProductRepository.findStandProductById(standTypeId);

        String fileName = multipartFile.getOriginalFilename();

        //--2023-11-21不需要版本，每次上传直接更新原来的BOM
        StandFileInfo standFileInfo1 = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId, category, 1, 0);
        if (standFileInfo1 != null) {
            standFileInfoRepository.delete(standFileInfo1);
        }
        //生成新的bomcode
        int val = standProduct.getBomSerial();
        val += 1;
        standProduct.setBomSerial(val);
//            String postfix = serialNumberService.getNextSnByCode("StandBomCodeSerial");
        String postfix = String.format("%03d", val);
        String prefix = standTypeCode.replace(".001.001", ".002");
        String fileCode = prefix + "." + postfix; //STD.C(TYPE).002.XXX

        StandFileInfoDto standFileInfoDto = new StandFileInfoDto();
        standFileInfoDto.setStandTypeId(standTypeId);
        standFileInfoDto.setStandTypeDesc(standTypeDesc);
        standFileInfoDto.setStandTypeCode(standTypeCode);
        standFileInfoDto.setStandTypeName(standTypeName);
        standFileInfoDto.setCategory(category);

        standFileInfoDto.setFileCode(fileCode);
        standFileInfoDto.setFileName(fileName);
        standFileInfoDto.setCategory(category);// BOM
        standFileInfoDto.setVersion(1);
        standFileInfoDto.setStatus(1);//启用
        standFileInfoDto.setMemo(memo);
        standFileInfoDto.setBucketName(bucketName);

        returnBomCodeAndVersion.add(fileCode);
        returnBomCodeAndVersion.add(1);

        BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
        standFileInfoDto.setFileSize(fileSize);
        standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".") + 1));

        //上传文件，用bomcode+filename+version;
        String uploadFileName = fileCode + "+" + String.valueOf(standFileInfoDto.getVersion()) + "+" + fileName;
//        String uploadFileName = fileCode + "+" + fileName;
        minioUtil.uploadFile(multipartFile, uploadFileName, bucketName);
        String preview_url = minioUtil.uploadFile2(multipartFile, uploadFileName, bucketName);
        standFileInfoDto.setFileUrl(preview_url);

        standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));
        //--2023-11-21不需要版本，每次上传直接更新原来的BOM

        //文件名一样，版本号迭代，编码一样，历史文件保留
//        List<StandFileInfo> standFileInfoList  = standFileInfoRepository.findStandFileInfosByStandTypeIdAndCategoryAndFileNameAndDelete(standTypeId,category,fileName,0);
//        if(standFileInfoList.size()==0){
//            //文件名不重复，版本号1，编码生成
//            //将启用的归档一下，status变为-1
//            StandFileInfo standFileInfo1 = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId,category,1,0);
//            if(standFileInfo1!=null){
//                standFileInfo1.setStatus(-1);
//                standFileInfoRepository.save(standFileInfo1);
//            }
//
//            //生成新的bomcode
//            int val = standProduct.getBomSerial();
//            val +=1;
//            standProduct.setBomSerial(val);
////            String postfix = serialNumberService.getNextSnByCode("StandBomCodeSerial");
//            String postfix  = String.format("%03d", val);
//            String prefix = standTypeCode.replace(".001.001",".002");
//            String fileCode = prefix + "." + postfix; //STD.C(TYPE).002.XXX
//
//            StandFileInfoDto standFileInfoDto = new StandFileInfoDto();
//            standFileInfoDto.setStandTypeId(standTypeId);
//            standFileInfoDto.setStandTypeDesc(standTypeDesc);
//            standFileInfoDto.setStandTypeCode(standTypeCode);
//            standFileInfoDto.setStandTypeName(standTypeName);
//            standFileInfoDto.setCategory(category);
//
//            standFileInfoDto.setFileCode(fileCode);
//            standFileInfoDto.setFileName(fileName);
//            standFileInfoDto.setCategory(category);// BOM
//            standFileInfoDto.setVersion(1);
//            standFileInfoDto.setStatus(1);//启用
//            standFileInfoDto.setMemo(memo);
//            standFileInfoDto.setBucketName(bucketName);
//
//            returnBomCodeAndVersion.add(fileCode);
//            returnBomCodeAndVersion.add(1);
//
//            BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
//            standFileInfoDto.setFileSize(fileSize);
//            standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".")+1));
//
//            //上传文件，用bomcode+filename+version;
//            String uploadFileName = fileCode+"+"+String.valueOf(standFileInfoDto.getVersion())+"+"+fileName ;
//            minioUtil.uploadFile(multipartFile,uploadFileName,bucketName);
//            String preview_url = minioUtil.uploadFile2(multipartFile,uploadFileName,bucketName);
//            standFileInfoDto.setFileUrl(preview_url);
//            //System.out.println("fileUrl"+fileUrl);
//
//            standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));
//            //standFileInfoService.addStandFileInfo(standFileInfoDto);
//
//        }
//        else{
//            //文件名一样，版本号迭代，编码一样，历史文件保留
//            //将启用的归档一下，status变为-1
//            StandFileInfo standFileInfo1 = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId,category,1,0);
//            if(standFileInfo1!=null){
//                standFileInfo1.setStatus(-1);
//                standFileInfoRepository.save(standFileInfo1);
//            }
//            StandFileInfo standFileInfo =new StandFileInfo();
//            int version = 0;
//            for(StandFileInfo standFileInfo2:standFileInfoList){
//                if(standFileInfo2.getVersion()>version){
//                    standFileInfo=standFileInfo2;
//                    version=standFileInfo2.getVersion();
//                }
//            }
//            StandFileInfoDto standFileInfoDto = standFileInfoMapper.toDto(standFileInfo);
//
//            //int version =standFileInfoDto.getVersion();
//            standFileInfoDto.setVersion(version+1);
//            standFileInfoDto.setCategory(category);// BOM
//            standFileInfoDto.setStatus(1);//启用
//            standFileInfoDto.setMemo(memo);
//
//            BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
//            standFileInfoDto.setFileSize(fileSize);
//            standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".")+1));
//
//            //上传文件，用bomcode+version+filename;
//            String fileCode = standFileInfoDto.getFileCode();
//            String uploadFileName = fileCode+"+"+String.valueOf(standFileInfoDto.getVersion())+"+"+fileName ;
//            String preview_url = minioUtil.uploadFile2(multipartFile,uploadFileName,bucketName);
//            standFileInfoDto.setFileUrl(preview_url);
//            //System.out.println("fileUrl"+fileUrl);
//
//            //之前版本的要保留，id为null，走新建逻辑
//            standFileInfoDto.setId(null);
//
//            returnBomCodeAndVersion.add(fileCode);
//            returnBomCodeAndVersion.add(standFileInfoDto.getVersion());
//
//            standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));
//            //standFileInfoService.updateStandFileInfo(standFileInfoDto);
//        }


        standProduct.setIsBomUpload(1);
        standProductRepository.save(standProduct);
        return returnBomCodeAndVersion;
    }

    @Override
    public void uploadStandFileInfoDrawing(String standTypeId, String standTypeDesc, String standTypeCode, String standTypeName, String category, MultipartFile[] multipartFiles, String memo, String bucketName) throws Exception {
        StandProduct standProduct = standProductRepository.findStandProductById(standTypeId);
        for (MultipartFile multipartFile : multipartFiles) {
            String fileName = multipartFile.getOriginalFilename();

            //--2023-11-21不需要版本，每次上传直接更新原来的BOM
            //同类别+同名，上传，覆盖
            //同类别+不同名/不同类别，上传，编号不一样

            List<StandFileInfo> standFileInfoList = standFileInfoRepository.findStandFileInfosByStandTypeIdAndCategoryAndFileNameAndDelete(standTypeId, category, fileName, 0);
            if (standFileInfoList.size() == 0) {
                //同类别+不同名/不同类别，上传，编号不一样

                //生成新的drawingcode
                int val = standProduct.getDrawingSerial();
                val += 1;
                standProduct.setDrawingSerial(val);
//                String postfix = serialNumberService.getNextSnByCode("StandDrawingCodeSerial");
                String postfix = String.format("%03d", val);

                String prefix = standTypeCode.replace(".001.001", ".003");
                String fileCode = prefix + "." + postfix;//STD.C(TYPE).003.XXX

                StandFileInfoDto standFileInfoDto = new StandFileInfoDto();
                standFileInfoDto.setStandTypeId(standTypeId);
                standFileInfoDto.setStandTypeDesc(standTypeDesc);
                standFileInfoDto.setStandTypeCode(standTypeCode);
                standFileInfoDto.setStandTypeName(standTypeName);
                standFileInfoDto.setCategory(category);

                standFileInfoDto.setFileCode(fileCode);
                standFileInfoDto.setFileName(fileName);
                standFileInfoDto.setCategory(category);// 图纸类别
                standFileInfoDto.setVersion(1);
                standFileInfoDto.setStatus(1);//启用
                standFileInfoDto.setMemo(memo);
                standFileInfoDto.setBucketName(bucketName);

                BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
                standFileInfoDto.setFileSize(fileSize);
                standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".") + 1));

                //上传文件，用drawingcode+version+filename;
                String uploadFileName = fileCode + "+" + String.valueOf(standFileInfoDto.getVersion()) + "+" + fileName;
                String preview_url = minioUtil.uploadFile2(multipartFile, uploadFileName, bucketName);
                standFileInfoDto.setFileUrl(preview_url);
                //System.out.println("fileUrl"+fileUrl);

                standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));
                //standFileInfoService.addStandFileInfo(standFileInfoDto);

            }
            else {
                //同类别+同名，上传，覆盖   standFileInfoList

                StandFileInfo standFileInfo = new StandFileInfo();
                int version = 0;
                for (StandFileInfo standFileInfo2 : standFileInfoList) {
                    if (standFileInfo2.getVersion() > version) {
                        standFileInfo = standFileInfo2;
                        version = standFileInfo2.getVersion();
                    }
                }
                StandFileInfoDto standFileInfoDto = standFileInfoMapper.toDto(standFileInfo);

                //int version =standFileInfoDto.getVersion();
                standFileInfoDto.setVersion(version + 1);
                standFileInfoDto.setStatus(1);//启用
                standFileInfoDto.setCategory(category);// 图纸类别
                standFileInfoDto.setMemo(memo);

                BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
                standFileInfoDto.setFileSize(fileSize);
                standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".") + 1));

                //上传文件，用drawingcode+version+filename;
                String fileCode = standFileInfoDto.getFileCode();
                String uploadFileName = fileCode + "+" + String.valueOf(standFileInfoDto.getVersion()) + "+" + fileName;
                //minioUtil.uploadFile(multipartFile,uploadFileName,bucketName);
                String preview_url = minioUtil.uploadFile2(multipartFile, uploadFileName, bucketName);
                standFileInfoDto.setFileUrl(preview_url);
                //System.out.println("fileUrl"+fileUrl);


                //之前版本的要保留，id为null，走新建逻辑
                standFileInfoDto.setId(null);

                standFileInfoRepository.deleteAll(standFileInfoList);

                standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));


                //standFileInfoService.updateStandFileInfo(standFileInfoDto);
            }




//            //文件名一样，版本号迭代，编码一样，历史文件保留
//            // StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndFileNameAndDelete(standTypeId,category,fileName,0);
//            List<StandFileInfo> standFileInfoList = standFileInfoRepository.findStandFileInfosByStandTypeIdAndCategoryAndFileNameAndDelete(standTypeId, category, fileName, 0);
//            if (standFileInfoList.size() == 0) {
//                //文件名不重复，版本号1，编码生成
//                //图纸额外更新一下 标准柜的字段信息
//                //将启用的归档一下，status变为-1
//                StandFileInfo standFileInfo1 = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId, category, 1, 0);
//                if (standFileInfo1 != null) {
//                    standFileInfo1.setStatus(-1);
//                    standFileInfoRepository.save(standFileInfo1);
//                }
//
//                //生成新的drawingcode
//                int val = standProduct.getDrawingSerial();
//                val += 1;
//                standProduct.setDrawingSerial(val);
////                String postfix = serialNumberService.getNextSnByCode("StandDrawingCodeSerial");
//                String postfix = String.format("%03d", val);
//
//                String prefix = standTypeCode.replace(".001.001", ".003");
//                String fileCode = prefix + "." + postfix;//STD.C(TYPE).003.XXX
//
//                StandFileInfoDto standFileInfoDto = new StandFileInfoDto();
//                standFileInfoDto.setStandTypeId(standTypeId);
//                standFileInfoDto.setStandTypeDesc(standTypeDesc);
//                standFileInfoDto.setStandTypeCode(standTypeCode);
//                standFileInfoDto.setStandTypeName(standTypeName);
//                standFileInfoDto.setCategory(category);
//
//                standFileInfoDto.setFileCode(fileCode);
//                standFileInfoDto.setFileName(fileName);
//                standFileInfoDto.setCategory(category);// 图纸类别
//                standFileInfoDto.setVersion(1);
//                standFileInfoDto.setStatus(1);//启用
//                standFileInfoDto.setMemo(memo);
//                standFileInfoDto.setBucketName(bucketName);
//
//                BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
//                standFileInfoDto.setFileSize(fileSize);
//                standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".") + 1));
//
//                //上传文件，用drawingcode+version+filename;
//                String uploadFileName = fileCode + "+" + String.valueOf(standFileInfoDto.getVersion()) + "+" + fileName;
//                String preview_url = minioUtil.uploadFile2(multipartFile, uploadFileName, bucketName);
//                standFileInfoDto.setFileUrl(preview_url);
//                //System.out.println("fileUrl"+fileUrl);
//
//                standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));
//                //standFileInfoService.addStandFileInfo(standFileInfoDto);
//
//            }
//            else {
//                //文件名一样，版本号迭代，编码一样，历史文件保留
//                //将启用的归档一下，status变为-1
//                StandFileInfo standFileInfo1 = standFileInfoRepository.findStandFileInfoByStandTypeIdAndCategoryAndStatusAndDelete(standTypeId, category, 1, 0);
//                if (standFileInfo1 != null) {
//                    standFileInfo1.setStatus(-1);
//                    standFileInfoRepository.save(standFileInfo1);
//                }
//
//                StandFileInfo standFileInfo = new StandFileInfo();
//                int version = 0;
//                for (StandFileInfo standFileInfo2 : standFileInfoList) {
//                    if (standFileInfo2.getVersion() > version) {
//                        standFileInfo = standFileInfo2;
//                        version = standFileInfo2.getVersion();
//                    }
//                }
//                StandFileInfoDto standFileInfoDto = standFileInfoMapper.toDto(standFileInfo);
//
//                //int version =standFileInfoDto.getVersion();
//                standFileInfoDto.setVersion(version + 1);
//                standFileInfoDto.setStatus(1);//启用
//                standFileInfoDto.setCategory(category);// 图纸类别
//                standFileInfoDto.setMemo(memo);
//
//                BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
//                standFileInfoDto.setFileSize(fileSize);
//                standFileInfoDto.setFileExtEndDate(fileName.substring(fileName.lastIndexOf(".") + 1));
//
//                //上传文件，用drawingcode+version+filename;
//                String fileCode = standFileInfoDto.getFileCode();
//                String uploadFileName = fileCode + "+" + String.valueOf(standFileInfoDto.getVersion()) + "+" + fileName;
//                //minioUtil.uploadFile(multipartFile,uploadFileName,bucketName);
//                String preview_url = minioUtil.uploadFile2(multipartFile, uploadFileName, bucketName);
//                standFileInfoDto.setFileUrl(preview_url);
//                //System.out.println("fileUrl"+fileUrl);
//
//
//                //之前版本的要保留，id为null，走新建逻辑
//                standFileInfoDto.setId(null);
//
//                standFileInfoRepository.save(standFileInfoMapper.toEntity(standFileInfoDto));
//                //standFileInfoService.updateStandFileInfo(standFileInfoDto);
//            }
            standProduct.setIsDrawingUpload(checkDrawingIsUpload(standProduct));
            standProductRepository.save(standProduct);
        }
    }

    public int checkDrawingIsUpload(StandProduct standProduct) {
        //箱柜接线表和电气原理图
        String standProductId = standProduct.getId();
        List<StandFileInfo> standFileInfoList = standFileInfoRepository.findStandFileInfosByStandTypeIdAndCategoryAndStatusAndDelete(standProductId, "电气原理图", 1, 0);
        if (standFileInfoList.size() == 0) return 0;
        List<StandFileInfo> standFileInfo1List = standFileInfoRepository.findStandFileInfosByStandTypeIdAndCategoryAndStatusAndDelete(standProductId, "箱柜接线表", 1, 0);
        if (standFileInfo1List.size() == 0) return 0;
        return 1;
    }


    @Override
    public void updateStandFileInfo(StandFileInfoDto standFileInfoDto) {
        StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoById(standFileInfoDto.getId());
        standFileInfo = standFileInfoMapper.toEntity(standFileInfoDto);
        standFileInfoRepository.save(standFileInfo);
    }


    @Override
    public StandFileInfo getFileByFileCode(String fileCode) {
        StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoByFileCode(fileCode);
        return standFileInfo;
    }


    @Override
    public void downloadStandFile(String standFileId, HttpServletResponse response){
        try {
            StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoByIdAndDelete(standFileId,0);
            String bucketName = standFileInfo.getBucketName();
            String fileName = standFileInfo.getFileName();
            int version =standFileInfo.getVersion();
            String fileCode = standFileInfo.getFileCode();
            String downloadFileName= fileCode+"+"+String.valueOf(version)+"+"+fileName;
            InputStream inputStream = minioService.downloadOne(bucketName, downloadFileName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+fileName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
        } catch (IOException e) {
            throw new BeadminException("下载失败");
        }
    }


    @Override
    public void delStandFileInfo(String id) {
        StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoByIdAndDelete(id, 0);
        standFileInfo.setDelete(1);
        if (standFileInfo.getStatus() == 1) standFileInfo.setStatus(-1);
        standFileInfoRepository.save(standFileInfo);
    }

    @Override
    public void delStandFileInfos(List<String> ids) {
    }

    @Override
    public List<String> getStandFileType() {
        DictType dictType = dictTypeRepository.findDictTypeByDictName("标准柜体附件上传类型");
        List<DictDataEx> standFileType = dictDataService.getDictDataExByDictTypeId(dictType);
        List<String> standFileTypeList = new ArrayList<>();
        standFileType.forEach(role -> standFileTypeList.add(role.getKeyName()));
        return standFileTypeList;
    }


}